package com.zhk.entry.util;

import java.sql.*;

/**
 * jdbc 工具类
 */
public class DbUtils {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/demo?\"\n" +
            "\t\t\t+ \"useUnicode=true&characterEncoding=UTF-8";

    private static final String UNAME = "root";
    private static final String PWD = "root";

    /***
     * 创建连接
     * @return
     * @throws Exception
     */
    public static Connection connectDB() {
        Connection conn = null;
        //1、加载数据库驱动
        try {
            Class.forName(DRIVER);
            //2、获取数据库连接
            conn = DriverManager.getConnection(URL, UNAME, PWD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return conn;
    }

    /**
     * 关闭连接
     *
     * @param connection
     * @param preparedStatement
     * @param resultSet
     */
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
